/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package orgarqsindex.linkedlist;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import orgarqsindex.RowModel;

/**
 *
 * @author Fernando Molon Toigo e Dyoni Bertuol
 */
public class LinkedListGenerator {

    private File sourceFile;
    private int rowSize;
    private int valueBeginIndex;
    private int valueSize;

    public LinkedListGenerator(File sourceFile, int rowSize, int valueBeginIndex, int valueSize) {
        this.sourceFile = sourceFile;
        this.rowSize = rowSize;
        this.valueBeginIndex = valueBeginIndex;
        this.valueSize = valueSize;
    }

    public LinkedListValueNode generate() throws FileNotFoundException, IOException {

        LinkedListValueNode root = null;

        RandomAccessFile sraf = new RandomAccessFile(sourceFile, "r");

        long lengthSourceFile = sraf.length();
        byte[] buffer = new byte[valueSize];

        //percorre todo o arquivo
        for (long i = 0; i < lengthSourceFile; i += rowSize) {
            sraf.seek(i + valueBeginIndex);
            sraf.read(buffer);
            String value = new String(buffer, "ISO-8859-1");
            value = value.trim();
            if (root == null) {
                root = new LinkedListValueNode(value);
            }
            root.insert(value, i / rowSize);
        }

        sraf.close();

        return root;
    }

    public void show(LinkedListValueNode linkedListRootNode, String value) throws FileNotFoundException, IOException {

        value = value.trim();

        RandomAccessFile sraf = new RandomAccessFile(sourceFile, "r");

        LinkedListValueNode currentValueNode = linkedListRootNode;
        while (currentValueNode != null && currentValueNode.getValue().compareToIgnoreCase(value) != 0) {
            currentValueNode = currentValueNode.nextValue;
        }

        if (currentValueNode == null) {
            System.out.println("Não encontrado!");
        } else {
            LinkedListAddressNode currentAddressNode = currentValueNode.nextAddress;
            byte[] buffer = new byte[rowSize];
            while (currentAddressNode != null) {
                sraf.seek(currentAddressNode.getAddress()*rowSize);
                sraf.read(buffer);
                RowModel rowFound = new RowModel(new String(buffer, "ISO-8859-1"));
                System.out.println(rowFound.toString());
                currentAddressNode = currentAddressNode.nextAddress;
            }
        }

        sraf.close();
    }
}
